<template>
  <main>
    <div class="common-layout">
      <el-container>
        <el-header>
<!--          <Top/>-->
        </el-header>
        <el-container>
          <el-aside>
<!--            <Menu/>-->
          </el-aside>
          <el-main>
            <!--搜索框-->
            <el-row class="search">
              <el-col :span="6">
                <el-input v-model="gname" style="width: 80%"  placeholder="商品名称" clearable/>
              </el-col>
              <el-col :span="6">
                <el-input v-model="gmodel" style="width: 80%" placeholder="商品型号" clearable/>
              </el-col>
<!--              添加商品-->
<!--              <el-button type="primary" @click="addFirstGoods">创建一类商品</el-button>-->
              <el-button type="primary" @click="addOpen">创建商品</el-button>
            </el-row>

            <div style="height: 20px;"></div>

            <el-row>
              <el-col :span="6">
              <el-select v-model="gcolor1" placeholder="商品颜色" style="width: 80%" clearable>
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              </el-col>
              <el-col :span="6">
                <el-select v-model="gbrand" placeholder="商品品牌" style="width: 80%" clearable>
                  <el-option
                      v-for="item in options3"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-select v-model="typeName" placeholder="商品分类" style="width: 80%" clearable>
                  <el-option
                      v-for="item in options4"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-col>
              <el-col :span="6" >
                <el-button type="success" @click="query">搜索</el-button>
              </el-col>
            </el-row>
            <div style="height: 20px;"></div>
            <el-row class="search">
<!--              <el-col :span="3">-->
<!--                <el-button type="success" @click="downloadTemplate">下载导入模版</el-button>-->
<!--              </el-col>-->
<!--              <el-col :span="3">-->
<!--                <el-upload class="upload-demo" method="post"-->
<!--                           action="http://127.0.0.1:8080/dynamic/up"-->
<!--                           :show-file-list="false"-->
<!--                           :with-credentials="true"-->
<!--                           :on-success="upsuccess"-->
<!--                           :on-error="uperror"-->
<!--                >-->
<!--                  <template #trigger>-->
<!--                    <el-button type="primary">导入</el-button>-->
<!--                  </template>-->
<!--                </el-upload>-->

<!--              </el-col>-->
<!--              <el-col :span="3">-->
<!--                <el-button type="danger" @click="exportExcel">导出</el-button>-->
<!--              </el-col>-->

            </el-row>


            <!-- 表格 -->
            <el-table ref="tableRef" :data="dynamicList" border style="width: 100%">

              <el-table-column prop="id" label="序号" fixed="left" width="80" />
              <el-table-column prop="gname" label="商品名称" width="100" />
              <el-table-column prop="typeName" label="商品分类" width="180" />
              <el-table-column prop="gbrand" label="商品品牌" width="180" />
              <el-table-column prop="gmodel" label="商品型号" width="180" />
              <el-table-column prop="gcolor" label="商品颜色" width="180" />
<!--              <el-table-column prop="ctime" label="发布时间" width="200" :formatter="formatTimestamp"/>-->
<!--              <el-table-column prop="type" label=" 类型" :formatter="formatType"/>-->
              <el-table-column label="操作" default="scope">
                <template #default="scope">
                  <el-button type="warning" size="small" @click="updateOpen(scope.row)">修改</el-button>
                  <el-button type="danger" size="small" @click="del(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination background
                           layout="total, sizes, prev, pager, next, jumper"
                           v-model:current-page="pageNum"
                           v-model:page-size="pageSize"
                           :page-sizes="[2,5, 10, 50]"
                           :total="total"
                           @size-change="query"
                           @current-change="query"/>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </main>


  <el-dialog
      v-model="addDialogVisible"
      title="创建商品"
      width="500"
  >
    <el-form ref="addFormRef"  :model="addForm.addData" label-width="90" >
      <el-form-item label="商品品牌" prop="gbrand" >
        <el-select v-model="addForm.addData.gbrand" placeholder="商品品牌" style="width: 80%" clearable>
          <el-option
              v-for="item in options3"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品型号" prop="gmodel" >
        <el-input v-model="addForm.addData.gmodel" placeholder="gmodel" />
      </el-form-item>
      <el-form-item label="商品颜色" prop="gcolor" >
        <el-select v-model="addForm.addData.gcolor" placeholder="商品颜色" style="width: 80%" clearable>
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="gname" >
        <el-input v-model="addForm.addData.gname" placeholder="gname" />
      </el-form-item>
      <el-form-item label="商品分类" prop="classify" >
        <el-select v-model="addForm.addData.typeName" placeholder="商品分类" style="width: 80%" clearable>
          <el-option
              v-for="item in options4"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市场价" prop="marketPrice" >
        <el-input v-model="addForm.addData.marketPrice" placeholder="marketPrice" />
      </el-form-item>
      <el-form-item label="商城价" prop="shopPrice" >
        <el-input v-model="addForm.addData.shopPrice" placeholder="shopPrice" />
      </el-form-item>
      <el-form-item label="最低库存量" prop="minStock" >
        <el-input v-model="addForm.addData.minStock" placeholder="minStock" />
      </el-form-item>
      <el-form-item label="是否可采购" prop="gstatus" >
        <el-select v-model="addForm.addData.gstatus" placeholder="gstatus" style="width: 240px" clearable  >
          <el-option label="可采购" :value="1" />
          <el-option label="不可采购" :value="0" />
        </el-select>
      </el-form-item>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetAdd">重置</el-button>
        <el-button type="primary" @click="addSecondGoods">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-dialog
      v-model="updateDialogVisible"
      title="修改"
      width="500"
  >
    <el-form ref="updateFormRef"  :model="updateForm.updateData" label-width="90" >
      <el-form-item label="存货档案编号" prop="gcode" >
        <el-input  v-model="updateForm.updateData.gcode" placeholder="gcode" disabled/>
      </el-form-item>
      <el-form-item label="基础库-分类:" prop="typeName" >
        <el-input v-model="updateForm.updateData.typeName" placeholder="typeName" disabled/>
      </el-form-item>
      <el-form-item label="基础库品牌:" prop="gbrand" >
        <el-input v-model="updateForm.updateData.gbrand" placeholder="gbrand" disabled/>
      </el-form-item>
      <el-form-item label="基础库-颜色:" prop="gcolor" >
        <el-input v-model="updateForm.updateData.gcolor" placeholder="gcolor" disabled/>
      </el-form-item>
      <el-form-item label="基础库-采购模式:" prop="purchasingPattern" >
        <el-input v-model="updateForm.updateData.purchasingPattern" placeholder="purchasingPattern" disabled/>
      </el-form-item>
      <el-form-item label="基础库-铺货:" prop="distribution" >
        <el-input v-model="updateForm.updateData.distribution" placeholder="distribution" disabled/>
      </el-form-item>
      <el-form-item label="基础库-备机:" prop="standby" >
        <el-input v-model="updateForm.updateData.standby" placeholder="standby" disabled/>
      </el-form-item>
      <el-form-item label="商品名称" prop="gname" >
        <el-input v-model="updateForm.updateData.gname" placeholder="gname" />
      </el-form-item>
      <el-form-item label="商品类别:" prop="classify" >
        <el-select v-model="updateForm.updateData.classify" placeholder="Select" style="width: 201px">
          <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市场价:" prop="marketPrice" >
        <el-input v-model="updateForm.updateData.marketPrice" placeholder="marketPrice" />
      </el-form-item>
      <el-form-item label="商城价:" prop="shopPrice" >
        <el-input v-model="updateForm.updateData.shopPrice" placeholder="shopPrice" />
      </el-form-item>
      <el-form-item label="最低库存量:" prop="minStock" >
        <el-input v-model="updateForm.updateData.minStock" placeholder="minStock" />
      </el-form-item>
      <el-form-item label="是否可采购:" prop="gstatus" >
        <el-select v-model="updateForm.updateData.gstatus" placeholder="Select" style="width: 201px">
          <el-option label="可采购" :value="0" />
          <el-option label="不可采购" :value="1" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetupdate">重置</el-button>
        <el-button type="primary" @click="updateSubmit">
          修改
        </el-button>
      </div>
    </template>
  </el-dialog>





</template>

<script setup>
// import Top from '../../components/Top.vue'
// import Menu from '../../components/Menu.vue'
import {ref, reactive, getCurrentInstance, onMounted, nextTick} from "vue";
import router from '@/router/index.js'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from '@/plugins/axios.js'

/*
* 公共变量
* */
const {proxy} = getCurrentInstance()



/**
 * 添加商品
 */
// let addFirstGoods = () => {
//   router.push({path: '/goods/addFirstGoods'})
// }
// let addSecondGoods = () => {
//   router.push({path: '/goods/addGoods'})
// }

const addFormRef = ref()
const addDialogVisible = ref(false)
const addForm = reactive({addData:{
    gcode:'',
    classify:'',
    gname:'',
    typeName:'',
    gbrand:'',
    gmodel:'',
    gcolor:'',
    purchasingPattern:'',
    distribution:'',
    standby:'',
    marketPrice:'',
    shopPrice:'',
    minStock:'',
    gstatus:''
  }})


const myUpload = (myfile)=>{

  //获取文件
  let currentFile = myfile.file;
  //创建form
  var formData = new FormData();
  //把文件放入form
  formData.append("myfile",currentFile);
  //请求使用post  传递form 设置请求头{headers: {'Content-Type': 'multipart/form-data'}}
  proxy.$axios.post("/imgUpload/upload",formData,{headers: {'Content-Type': 'multipart/form-data'}})
      .then(resp=>{

        //处理响应图片预览
        addForm.addData.gameicon = resp.data.returnData;//???
        console.log(addForm.addData.gameicon)
      })

}
const myUpload3 = (myfile)=>{

  //获取文件
  let currentFile = myfile.file;
  //创建form
  var formData = new FormData();
  //把文件放入form
  formData.append("myfile",currentFile);
  //请求使用post  传递form 设置请求头{headers: {'Content-Type': 'multipart/form-data'}}
  proxy.$axios.post("/imgUpload/upload",formData,{headers: {'Content-Type': 'multipart/form-data'}})
      .then(resp=>{

        //处理响应图片预览
        addForm.addData.picture = resp.data.returnData;//???
        console.log(addForm.addData.picture)
      })

}
const addOpen = ()=>{
  addDialogVisible.value = true;
  //执行顺序  组件延迟加载
  // if(addFormRef.value != undefined){
  //   addFormRef.value.resetFields();
  // }
  //vue提供的函数 在一次渲染后 执行指定的代码
  //渲染时机后移
  nextTick(()=>{
    addFormRef.value.resetFields();//?
  })


}
const addSecondGoods = ()=>{
  addDialogVisible.value = false;
  let params = JSON.stringify(addForm.addData);
  // let params = proxy.$qs.stringify(addForm.addData);axios.postJson(url, param).
  //JSON.parse(JSON.stringify(addForm.addData));
  //console.log(params)
  //操作数据 刷新页面数据
  operationData("goods/addGoods",params)


}
const resetAdd = ()=>{
  addFormRef.value.resetFields();
}



/**
 * 搜索
 * @type {Ref<UnwrapRef<*[]>>}
 */
const queryForm = ref({
  color:'',
  type:''
})
/**
 *
 * 下拉框
 */
const gcolor1 = ref("")
const gbrand = ref("")
const typeName = ref("")
const options = [
  {
    value: '珍珠白',
    label: '珍珠白',
  },
  {
    value: '海湾蓝',
    label: '海湾蓝',
  },
  {
    value: '建窑紫',
    label: '建窑紫',
  },
  {
    value: '五彩斑斓的黑',
    label: '五彩斑斓的黑',
  }
]

const options3 = [
  {
    value: '苹果',
    label: '苹果',
  },
  {
    value: '华为',
    label: '华为',
  },
  {
    value: '东来也',
    label: '东来也',
  },
  {
    value: '小米',
    label: '小米',
  },
  {
    value: '品胜',
    label: '品胜',
  },
  {
    value: '魅族',
    label: '魅族',
  }
]

const options4 = [
  {
    value: '5G手机',
    label: '5G手机',
  },
  {
    value: '4G手机',
    label: '4G手机',
  },
  {
    value: '手机壳',
    label: '手机壳',
  },
  {
    value: '智能手表',
    label: '智能手表',
  },
  {
    value: '手机配件',
    label: '手机配件',
  },
  {
    value: '电脑音箱',
    label: '电脑音箱',
  }
]


/****************************************** **/


let dynamicList = ref([])

let gname = ref("")
let gmodel = ref("")
// let start_time = ref("")
// let end_time = ref("")
let total = ref(0)
let pageNum = ref(1)
let pageSize = ref(10)
let upsuccess = () => {
  ElMessage({
    type: "success",
    message: "上传成功"
  })
}
let uperror = () => {
  ElMessage({
    type: "danger",
    message: "上传失败"
  })
}
let query = () => {
  let url = "/goods/list";
  let param = {
    "pageSize": pageSize.value,
    "pageNum": pageNum.value,
    "gname": gname.value,
    "gmodel": gmodel.value,
    "gcolor": gcolor1.value,
    "typeName": typeName.value,
    "gbrand": gbrand.value
  }
  //console.log(param)
  axios.postJson(url, param).then(result => {
    //console.log("------------结果是"+result.gbrand)
    dynamicList.value = result.data.records;

    //首次查询直接给更新表单赋值
    // updateForm.value=result.data.records;
    // console.log(updateForm.gname+"----------------------修改表单的值")
    total.value = result.data.total;
  })

}
let exportExcel = () => {
  window.location.href = "http://127.0.0.1:8080/dynamic/export"
}
let downloadTemplate = () => {
  window.location.href = "http://127.0.0.1:8080/dynamic/template"
}
let formatTimestamp = (row)=>{
  const date = new Date(row.ctime);
  return date.toLocaleString(); // 根据本地时间格式显示
}
// let formatType = (row)=>{
//   switch (row.type) {
//     case 0:
//       return '文字动态';
//     case 1:
//       return '图片动态';
//     case 2:
//       return '视频动态';
//     case 3:
//       return '话题动态';
//     default:
//       return '未知'
//   }
// }

/**
* 修改功能
*
 *
 *

* */

const updateFormRef = ref()
const updateDialogVisible = ref(false)
const updateForm = reactive({updateData:{
    gcode:'',
    classify:'',
    gname:'',
    typeName:'',
    gbrand:'',
    gmodel:'',
    gcolor:'',
    purchasingPattern:'',
    distribution:'',
    standby:'',
    marketPrice:'',
    shopPrice:'',
    minStock:'',
    gstatus:'',
  }})

let tempUpdateData = {};

const updateOpen = (currentRow)=>{
  updateDialogVisible.value = true
  /* 从页面直接取值*/
  // let newJsonObj = JSON.parse(JSON.stringify(currentRow))
  // //console.log(JSON.parse(JSON.stringify(currentRow)))
  // updateForm.value = newJsonObj
  //console.log(currentRow)

  /*从服务接口取值*/
  let url = "/goods/selectGoodsWithGid";
  let param = {
    "gid": currentRow.id
  }
  axios.postJson(url, param)
      .then(resp=>{
        updateForm.updateData = resp.data;
        tempUpdateData = JSON.parse(JSON.stringify(resp.data));
      })


}

const updateSubmit = ()=>{
  updateDialogVisible.value = false;
  // let params = proxy.$qs.stringify(updateForm.updateData);
  //updateForm.updateData,把json
  let params = JSON.stringify(updateForm.updateData)
  // let params = JSON.parse(JSON.stringify(updateForm.updateData))
  console.log("------------修改数据是"+params)
  //操作数据 刷新页面数据
  operationData("goods/updateGoods",params)


}

const resetupdate = ()=>{

  updateForm.updateData = JSON.parse(JSON.stringify(tempUpdateData));

  updateFormRef.value.resetFields();

  console.log(tempUpdateData)

}

const options2 = [
  {
    value: '5G手机',
    label: '5G手机',
  },
  {
    value: '4G手机',
    label: '4G手机',
  },
  {
    value: '充电线',
    label: '充电线',
  },
  {
    value: '手机壳',
    label: '手机壳',
  },
  {
    value: '充电器',
    label: '充电器',
  },
  {
    value: '智能手表',
    label: '智能手表',
  },
  {
    value: '智能手环',
    label: '智能手环',
  }
]



/**
* 删除功能
*
 */
const tableRef = ref();
const del=(gid)=>{
  //console.log(gid)

  ElMessageBox.confirm(
      `确定删除编号为[${gid}]的数据么`,
      '删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        console.log('发送ajax请求删除数据')
        let param = {
          "gid": gid
        }
        operationData("goods/deleteGoods",param)


      })
      .catch(() => {
        ElMessage.info("取消删除")
      })




}

/**
 * 公共方法
 */

/*
* 公共函数
* */
const queryData = (params)=>{
  proxy.$axios.get(`goods/list?${params}`)
      .then((resp)=>{
        if (resp.data.returnCode == 80011){
          //给table更新数据
          tableList.tableData =resp.data.returnData
          //给分页组件更新数据
          pageInfo.pageData = resp.data.pageInfo
          console.log("---=---"+pageInfo.pageData)
          console.log(tableList.tableData)
          // queryData(params)
        }else if(resp.data.returnCode == 80012){
          //如果没有数据 保证组件正常使用
          tableList.tableData = [];
          pageInfo.pageData ={page:1,pageSize:5,total:0}
        }

      })
}

const operationData=(url,params)=>{
  axios.postJson(url, params)
      .then(resp=>{
        //1.弹窗显示结果
        console.log(resp.data)
        if(resp.code == 200){
          ElMessage.success("操作成功!")
        }else {
          ElMessage.error("操作失败!")
        }
        //2.刷新数据
          query();


        //用当前查询参数查数据
        //let params = JSON.parse(JSON.stringify(pageInfo.pageData))
        //let params2 = JSON.parse(JSON.stringify(queryForm.value))
        //talbe数据
        // let params = proxy.$qs.stringify(pageInfo.pageData)
        // let params2 = proxy.$qs.stringify(queryForm.value)
        //queryData(params+'&'+params2)


        //重新查下拉列表
        // querySelect()
      })
}



onMounted(() => {
  query();
})
</script>

<style scoped>

</style>